#include "db_manager.hpp"
#include <stdexcept>

DBManager& DBManager::getInstance() {
    static DBManager instance;
    return instance;
}

bool DBManager::init(const std::string& host, 
                    const std::string& port,
                    const std::string& user,
                    const std::string& password,
                    const std::string& database) {
    if (mysql_) {
        mysql_close(mysql_);
    }
    
    mysql_ = mysql_init(nullptr);
    if (!mysql_) {
        return false;
    }
    
    if (!mysql_real_connect(mysql_,
                           host.c_str(),
                           user.c_str(),
                           password.c_str(),
                           database.c_str(),
                           std::stoi(port),
                           nullptr,
                           0)) {
        mysql_close(mysql_);
        mysql_ = nullptr;
        return false;
    }
    
    return true;
}

bool DBManager::connect(const std::string& host, 
                       const std::string& port,
                       const std::string& user,
                       const std::string& password,
                       const std::string& database) {
    return init(host, port, user, password, database);
}

DBManager::~DBManager() {
    if (mysql_) {
        mysql_close(mysql_);
    }
} 